//
//  WBUserAccount.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/6/7.
//  Copyright © 2018年 中发. All rights reserved.
//

import UIKit

private let accountFile: NSString = "userAccount.json"

class WBUserAccount: NSObject {

    //访问令牌
    var access_token: String? //= "2.00jE1m5CbBkY2De190d6c8fd0FgAyI"
    //用户代号
    var uid: String? = "2198414645"
    //过期时间
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expiresDate: Date?
    //用户昵称
    var screen_name: String?
    //用户头像地址
    var avatar_large: String?
    
    
    override var description: String {
        return yy_modelDescription()
    }
    override init() {
        super.init()
        
        //从磁盘加载保存的 文件--->字典
        //加载磁盘文件到二进制数据，如果失败则直接返回
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent(accountFile as String)
        
        
        guard let data = NSData(contentsOfFile: jsonPath),let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: Any] else {
            return
        }
        //使用字典设置属性值
        yy_modelSet(with: dict ?? [:])
        //判断Token是否过期
//        expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        //测试过期日期，开发中，每一个分支都要测试
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            //清空token
            access_token = nil
            uid = nil
            //删除账户文件
            try? FileManager.default.removeItem(atPath: jsonPath)
        }
    }
    
    /**
     1.偏好设置（小）
     2.沙盒--plist/归档/json
     3.数据库（FMDB/CoreData）
     4.钥匙串访问（小，自动加密 - 需要使用框架SSKeychain）
     */
    func saveAccount() {
        //1.模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String: Any]) ?? [:]
        
        //--删除expires_in值
        dict.removeValue(forKey: "expires_in")
        //2.字典序列号data
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else{
            return
        }
        
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent(accountFile as String)
        
        //3.写入磁盘
        (data as NSData).write(toFile: jsonPath, atomically: true)
        print("用户账户保存成功\(jsonPath)")
    }
}
